// firstpages/authorization/indedx.js
const app = getApp() // 引入app
import _request from '../../utils/request.js'
import md5 from '../../utils/md5.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    key: app.globalData.key, //全局img路径
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    sessionKey: '',
    openId: '',
    UserInfoObj: null,
    phoneNumber: ''
  },

  // 上传位置
  postXcxSave(latitude, longitude, city, userId) {
    _request.postObj('/userLocation/xcxsave', {
      userId,
      latitude,
      longitude,
      name: city,
    }).then((res) => {}).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 获取手机号码
  getPhoneNumber(e) {
    let msg = e.detail.errMsg;
    let that = this;
    let sessionID = this.data.sessionKey,
      encryptedDataStr = e.detail.encryptedData,
      iv = e.detail.iv;
    if (msg == 'getPhoneNumber:ok') {
      wx.checkSession({
        success: function (res) {
          that.deciyption(sessionID, encryptedDataStr, iv);
        },
        fail: function () {
          wx.login({
            success: (res) => {
              that.getwxAppletlogin(res.code)
              that.deciyption(sessionID, encryptedDataStr, iv);
            }
          })
        }
      })
    }
  },
  deciyption(sessionID, encryptedDataStr, iv) {
    let that = this
    _request.postObj('/storeUser/wxDecrypt', {
      client: "Applet",
      encryptedData: encryptedDataStr,
      iv: iv,
      sessionKey: sessionID
    }).then((res) => {
      this.setData({
        phoneNumber: JSON.parse(res.data.data).phoneNumber
      })
      // 获取用户头像
      wx.getUserInfo({
        success: function(res) {
          let headImg = res.userInfo.avatarUrl
          that.goLogin(that.data.phoneNumber,that.data.openId,headImg)
        }
      })
    })
  },

  // 获取用户信息
  getUserInfo() {
    console.log("aaaa")
    wx.getUserProfile({
      desc: 'Wexin', // 这个参数是必须的
      success: res => {
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  // 获取密钥key
  getwxAppletlogin(code) {
    _request.get('/storeUser/wxAppletlogin', {
      code: code,
      client: 'Applet'
    }).then(res => {
      this.setData({
        sessionKey: res.data.data.sessionKey,
        openId: res.data.data.openId
      })
      if (res.data.data.id) {
        this.setData({
          phoneNumber: res.data.data.mobile
        })
        wx.setStorageSync('userid', res.data.data.id)
        wx.setStorageSync('user', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        wx.setStorageSync('userId', res.data.data.id)
        if (res.data.data.storeId && res.data.data.storeId != null) {
          // 存在说明已经成为门店
          wx.setStorageSync('storeId', res.data.data.storeId)
          wx.reLaunch({
            url: '/firstpages/home/index',
          })
        } else {
          // 如果没有美发师id就去完善资料
          wx.reLaunch({
            url: '/firstpages/information/index',
          })
        }
      }
    })
  },
  // 登录
  goLogin(mobile, openId, img) {
    let signData = md5.hex(openId + "&" + mobile + "&" + this.data.key);
    _request.postObj('/storeUser/loginWXAdds', {
      client: "Applet",
      headImg: img,
      mobile: mobile,
      openId: openId,
      signData: signData,
      type: 3,
    }).then(res => {
      this.setData({
        sessionKey: res.data.data.sessionKey,
        openId: res.data.data.openId
      })
      if (res.data.code === 200) {
        wx.setStorageSync('userid', res.data.data.id)
        wx.setStorageSync('userId', res.data.data.id)
        wx.setStorageSync('user', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        let status = res.data.data.firstData.firstLogin
        // this.postXcxSave('22.547', '114.085947', '深圳市', res.data.data.id)
        if (res.data.data.storeId && res.data.data.storeId != null) {
          wx.setStorageSync('storeId', res.data.data.storeId)
          wx.switchTab({
            url: '/firstpages/home/index',
          })
        } else if (!res.data.data.storeId && res.data.data.storeId == null) {
          wx.reLaunch({
            url: '/firstpages/information/index',
          })
        }
        // this.checkMobile()
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 验证手机号
  checkMobile() {
    let that = this
    _request.get('/user/checkMobile', {
      mobile: this.data.phoneNumber
    }).then((res) => {})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo()
    let that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                UserInfoObj: res.data,
              })
              // 根据自己的需求有其他操作再补充
              // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
              wx.login({
                success: res => {
                  // 获取到用户的 code 之后：res.code}
                  // console.log(res.code,'res.code');
                  that.getwxAppletlogin(res.code)
                }
              });
            }
          });
        } else {
          // 用户没有授权
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})